<template>
  <div class="modal">
    <!-- 解决新增修改时 upload组件图片始终显示第一次的资源
     :visible.sync="dialogVisible"
    v-if="dialogVisible"
    -->
    <el-dialog
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="isNewRef ? '新建用户' : '编辑用户'"
      width="30%"
      center
    >
      <div class="form">
        <el-form :model="formData" label-width="100px" size="large">
          <el-form-item label="用户名" prop="nick_name">
            <el-input v-model="formData.nick_name" placeholder="请输入用户名" />
          </el-form-item>

          <el-form-item label="真实姓名" prop="user_name">
            <el-input v-model="formData.user_name" placeholder="请输入真实姓名" />
          </el-form-item>

          <el-form-item v-if="isNewRef" label="密码" prop="password">
            <el-input v-model="formData.password" placeholder="请输入密码" show-password />
          </el-form-item>

          <el-form-item v-if="isNewRef" label="再次输入密码" prop="re_password">
            <el-input
              v-model="formData.re_password"
              show-password
              placeholder="请再次输入输入密码"
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="tel">
            <el-input v-model="formData.tel" placeholder="请输入手机号码" />
          </el-form-item>

          <el-form-item label="email" prop="email">
            <el-input v-model="formData.email" placeholder="请输入email" />
          </el-form-item>

          <el-form-item label="选择角色" prop="roleId">
            <el-select v-model="formData.roleId" placeholder="请选择角色" style="width: 100%">
              <template v-for="item in entireRoles" :key="item.id">
                <el-option :label="item.name" :value="item.id" />
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="选择部门" prop="departmentId">
            <el-select v-model="formData.departmentId" placeholder="请选择部门" style="width: 100%">
              <template v-for="item in entireDepartments" :key="item.id">
                <el-option :label="item.name" :value="item.id" />
              </template>
            </el-select>
          </el-form-item>

          <el-form-item label="头像">
            <Upload
              :pic-list="formData.imgs"
              :upload-data="uploadData"
              :sign-conf="imgConfig.img"
              :pic-url="imgConfig.picUrl"
              :bucket="imgConfig.bucket"
              @setImg="setImg($event)"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import Upload from '@/components/upload/upload.vue'
import { ElMessage } from 'element-plus'
import {
  getRoleListRequest,
  getDepartmentsListRequest,
  addUserRequest,
  getQiNiuTokenRequest,
  getUserInfoRequest,
} from '@/service/Pub.ts'
// 1.定义内部的属性
const dialogVisible = ref(false)

const formData = reactive<any>({
  // id: 0,
  nick_name: '',
  user_name: '',
  password: '',
  re_password: '',
  email: '',
  tel: '',
  roleId: '',
  departmentId: '',
  imgs: [
    // {
    //   name: 'food.jpeg',
    //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    // },
    // {
    //   name: 'food.jpeg',
    //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    // },
  ],
})

const imgConfig = reactive<any>({
  picUrl: '',
  bucket: '',
  img: 'img',
})

const uploadData = reactive<any>({
  token: '',
})

const isNewRef = ref(true)
const editData = ref()

type RoleStr = {
  name: string
  id: number
}

// 2.获取roles/departments数据
const entireRoles = ref<RoleStr[]>([])
const entireDepartments = ref([])

// 获取子组件数据
function setImg(data) {
  console.log(999)
  formData.imgs = data.imgList
  console.log(formData.imgs)
}

//  ------------------------- 无用 -------------------------
// function updateImg(data) {
//   console.log('子组件监听')
//   console.log(data)
//   formData.img = data
// }
//  ------------------------- 无用 -------------------------

// 获取token
function getToken() {
  getQiNiuTokenRequest()
    .then((response) => {
      uploadData.token = response.data.token
      imgConfig.picUrl = response.data.picUrl
      imgConfig.bucket = response.data.bucket
    })
    .catch(() => {})
}

// 获取权限
function getRoleSel() {
  getRoleListRequest(1).then((res) => {
    entireRoles.value = res.data
  })
}

// 获取部门
function getDepartSel() {
  getDepartmentsListRequest(1).then((res) => {
    entireDepartments.value = res.data
  })
}

// watch(
//   () => formData.imgs,
//   async (newImgs) => {
//     formData.imgs = newImgs
//     dialogVisible.value = true
//     console.log('imgs属性发生变化:', formData.imgs)
//   },
// )

function getDetailUserInfo(uid: number) {
  getUserInfoRequest(uid)
    .then((response) => {
      formData.id = response.data.id
      formData.nick_name = response.data.nick_name
      formData.user_name = response.data.name
      formData.password = response.data.password
      formData.re_password = response.data.password
      formData.email = response.data.email
      formData.tel = response.data.tel
      formData.roleId = response.data.roleId
      formData.departmentId = response.data.departmentId
      formData.imgs = response.data.imgs
      console.log('imgs 新数据:', formData.imgs)
      dialogVisible.value = true
    })
    .catch(() => {})
}

// 2.定义设置dialogVisible方法
function setModalVisible(isNew: boolean = true, itemData?: any) {
  isNewRef.value = isNew
  if (!isNew && itemData) {
    // 编辑数据
    getDetailUserInfo(itemData.id)
  } else {
    // 新建数据
    // for (const key in formData) {
    //   formData[key] = ''
    // }
    formData.id = 0
    formData.nick_name = ''
    formData.user_name = ''
    formData.password = ''
    formData.re_password = ''
    formData.email = ''
    formData.tel = ''
    formData.roleId = ''
    formData.departmentId = ''
    formData.imgs = []
    console.log('formData============')
    console.log(formData.imgs)
    editData.value = null
    dialogVisible.value = true
  }
}

// 3.点击了确定的逻辑
function handleConfirmClick() {
  dialogVisible.value = false
  if (!isNewRef.value && editData.value) {
    // 编辑用户的数据
    editUserDataAction(editData.value.id, formData)
  } else {
    // 创建新的用户
    newUserDataAction(formData)
  }
}

function newUserDataAction(formData: any) {
  addUserRequest(formData).then((res) => {
    console.log('新增 =====================')
    console.log(formData)
    if (res.code == 200) {
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
    handleAddClick()
  })
}

const emit = defineEmits(['addClick'])
// 流程 -》 发送给父组件，再发送给content 兄弟组件
function handleAddClick() {
  // 把点击时事件发送到父页面    父页面 <USearch @query-click="userHandleQueryClick" /> query-click 一定是中横线
  // 最后再把事件发送给兄弟组件
  emit('addClick')
}

function editUserDataAction(id: number, formData: any) {
  console.log('更新')
}

// 暴露的属性和方法
defineExpose({ setModalVisible, getRoleSel, getDepartSel, getToken })
</script>

<style lang="less" scoped>
.form {
  padding: 0 20px;
}
</style>
